const moment = require('moment');
const db = require('../config/db');

/**
 * 买家控制器 - 处理买家特有功能
 * 包含订单管理等买家权限操作
 */

/**
 * 创建订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.createOrder = async (req, res) => {
  try {
    const buyerId = req.user.user_id;
    const { product_id, price, seller_id } = req.body;

    // 验证参数
    if (!product_id || !price || !seller_id) {
      return res.status(400).json({ success: false, error: '缺少必要参数' });
    }

    // 生成订单编号
    const orderNo = 'ORD' + moment().format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 1000);

    // 插入订单数据
    const [result] = await db.execute(
      'INSERT INTO orders (order_no, buyer_id, seller_id, product_id, price, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?)',
      [orderNo, buyerId, seller_id, product_id, price, moment().format('YYYY-MM-DD HH:mm:ss'), moment().format('YYYY-MM-DD HH:mm:ss')]
    );

    const orderId = result.insertId;

    // 记录创建订单日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家创建订单] 订单ID: ${orderId}, 订单编号: ${orderNo}, 买家ID: ${buyerId}, 商品ID: ${product_id}`);

    res.json({ success: true, order_id: orderId, order_no: orderNo });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [买家创建订单失败] ${error.message}`);
    res.status(500).json({ success: false, error: '创建订单失败' });
  }
};

/**
 * 创建交易记录
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.createTransaction = async (req, res) => {
  try {
    const buyerId = req.user.user_id;
    const { order_id, amount, payment_method } = req.body;

    // 验证参数
    if (!order_id || !amount || !payment_method) {
      return res.status(400).json({ success: false, error: '缺少必要参数' });
    }

    // 检查订单是否存在且属于当前买家
    const [orders] = await db.execute(
      'SELECT * FROM orders WHERE order_id = ? AND buyer_id = ?',
      [order_id, buyerId]
    );

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '订单不存在或不属于当前买家' });
    }

    // 生成交易号
    const transactionNo = 'TRA' + moment().format('YYYYMMDDHHmmss') + Math.floor(Math.random() * 1000);

    // 插入交易记录
    const [result] = await db.execute(
      'INSERT INTO transactions (order_id, amount, payment_method, transaction_no, status, created_at) VALUES (?, ?, ?, ?, 0, ?)',
      [order_id, amount, payment_method, transactionNo, moment().format('YYYY-MM-DD HH:mm:ss')]
    );

    const transactionId = result.insertId;

    // 记录创建交易日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家创建交易记录] 交易ID: ${transactionId}, 订单ID: ${order_id}, 买家ID: ${buyerId}`);

    res.json({ success: true, transaction_id: transactionId, transaction_no: transactionNo });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [买家创建交易记录失败] ${error.message}`);
    res.status(500).json({ success: false, error: '创建交易记录失败' });
  }
};



/**
 * 获取买家订单列表（支持分页和筛选）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getOrders = async (req, res) => {
  try {
    const buyerId = req.user.user_id;
    const { orderId, productName, status, startDate, endDate, page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    const queryParams = [];
    const countParams = [];
    let query = `
      SELECT o.order_id, o.product_id, p.title AS product_name, o.seller_id, u.username AS seller_name, 
             CAST(o.price AS DECIMAL(10,2)) AS total_amount, o.status, o.created_at, o.updated_at
      FROM orders o
      JOIN products p ON o.product_id = p.product_id
      JOIN users u ON o.seller_id = u.user_id
      WHERE o.buyer_id = ?
    `;
    let countQuery = `
      SELECT COUNT(*) as total
      FROM orders o
      JOIN products p ON o.product_id = p.product_id
      JOIN users u ON o.seller_id = u.user_id
      WHERE o.buyer_id = ?
    `;

    queryParams.push(buyerId);
    countParams.push(buyerId);

    // 构建查询条件
    if (orderId) {
      query += ' AND o.order_id LIKE ?';
      countQuery += ' AND o.order_id LIKE ?';
      queryParams.push(`%${orderId}%`);
      countParams.push(`%${orderId}%`);
    }

    if (productName) {
      query += ' AND p.title LIKE ?';
      countQuery += ' AND p.title LIKE ?';
      queryParams.push(`%${productName}%`);
      countParams.push(`%${productName}%`);
    }

    if (status !== undefined) {
      query += ' AND o.status = ?';
      countQuery += ' AND o.status = ?';
      queryParams.push(parseInt(status, 10));
      countParams.push(parseInt(status, 10));
    }

    if (startDate) {
      query += ' AND o.created_at >= ?';
      countQuery += ' AND o.created_at >= ?';
      queryParams.push(startDate);
      countParams.push(startDate);
    }

    if (endDate) {
      query += ' AND o.created_at <= ?';
      countQuery += ' AND o.created_at <= ?';
      queryParams.push(endDate);
      countParams.push(endDate);
    }

    // 添加排序逻辑
    query += ' ORDER BY o.created_at DESC';

    // 添加分页参数
    query += ' LIMIT ? OFFSET ?';
    queryParams.push(itemsPerPage, offset);

    // 输出调试信息
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [买家获取订单列表] SQL: ${query}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [买家获取订单列表] 参数: ${JSON.stringify(queryParams)}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [买家获取订单列表] 计数SQL: ${countQuery}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [买家获取订单列表] 计数参数: ${JSON.stringify(countParams)}`);

    // 执行查询
    const [orders] = await db.query(query, queryParams);
    const [countResult] = await db.query(countQuery, countParams);

    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    // 记录查询日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家订单查询] 买家ID: ${buyerId}, 请求参数: ${JSON.stringify(req.query)}, 总数量: ${totalItems}, 当前页: ${currentPage}`);

    res.json({
      success: true,
      orders,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [买家订单查询失败] ${error.message}`);
    res.status(500).json({ success: false, error: '获取订单列表失败' });
  }
};

/**
 * 支付订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.payOrder = async (req, res) => {
  try {
    const buyerId = req.user.user_id;
    const { order_id } = req.params;

    // 检查订单是否存在且属于当前买家
    const [orders] = await db.execute(
      'SELECT * FROM orders WHERE order_id = ? AND buyer_id = ?',
      [order_id, buyerId]
    );

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '订单不存在或不属于当前买家' });
    }

    const order = orders[0];

    // 检查订单状态是否允许支付
    if (order.status !== 0) {
      return res.status(400).json({ success: false, error: '当前订单状态不允许进行支付操作' });
    }

    // 更新订单状态为已付款
    await db.execute(
      'UPDATE orders SET status = 1, updated_at = ? WHERE order_id = ?',
      [moment().format('YYYY-MM-DD HH:mm:ss'), order_id]
    );

    // 同步更新交易记录状态为成功
    await db.execute(
      'UPDATE transactions SET status = 1 WHERE order_id = ?',
      [order_id]
    );

    // 记录支付日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家支付订单] 订单ID: ${order_id}, 买家ID: ${buyerId}`);

    res.json({ success: true, message: '订单支付成功' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [买家支付订单失败] ${error.message}`);
    res.status(500).json({ success: false, error: '支付订单失败' });
  }
};

/**
 * 确认收货或完成交易
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateOrderStatus = async (req, res) => {
  try {
    const buyerId = req.user.user_id;
    const { order_id } = req.params;

    // 检查订单是否存在且属于当前买家
    const [orders] = await db.execute(
      'SELECT * FROM orders WHERE order_id = ? AND buyer_id = ?',
      [order_id, buyerId]
    );

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '订单不存在或不属于当前买家' });
    }

    const order = orders[0];
    let newStatus = 3; // 默认更新为已收货
    let successMessage = '已确认收货';

    // 检查订单状态是否允许操作
    if (order.status === 1) {
      // 已付款状态 -> 已收货
      newStatus = 3;
      successMessage = '已确认收货';
    } else if (order.status === 2) {
      // 已发货状态 -> 已完成
      newStatus = 4;
      successMessage = '交易已完成';
    } else {
      return res.status(400).json({ success: false, error: '当前订单状态不允许进行此操作' });
    }

    // 更新订单状态
    await db.execute(
      'UPDATE orders SET status = ?, updated_at = ? WHERE order_id = ?',
      [newStatus, moment().format('YYYY-MM-DD HH:mm:ss'), order_id]
    );

    // 如果订单完成，同步更新交易记录状态为成功，并将商品状态更新为已售
    if (newStatus === 4) {
      await db.execute(
        'UPDATE transactions SET status = 1 WHERE order_id = ?',
        [order_id]
      );
      
      // 获取订单对应的商品ID
      const [orderDetails] = await db.execute(
        'SELECT product_id FROM orders WHERE order_id = ?',
        [order_id]
      );
      
      if (orderDetails.length > 0) {
        const productId = orderDetails[0].product_id;
        // 更新商品状态为已售
        await db.execute(
          'UPDATE products SET status = 2 WHERE product_id = ?',
          [productId]
        );
        console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家订单完成] 更新商品状态为已售，商品ID: ${productId}`);
      }
    }

    // 记录操作日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家确认操作] 订单ID: ${order_id}, 买家ID: ${buyerId}, 原状态: ${order.status}, 新状态: ${newStatus}`);

    res.json({ success: true, message: successMessage });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [买家确认操作失败] ${error.message}`);
    res.status(500).json({ success: false, error: '操作失败' });
  }
};

/**
 * 取消订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.cancelOrder = async (req, res) => {
  try {
    const buyerId = req.user.user_id;
    const { order_id } = req.params;

    // 检查订单是否存在且属于当前买家
    const [orders] = await db.execute(
      'SELECT * FROM orders WHERE order_id = ? AND buyer_id = ?',
      [order_id, buyerId]
    );

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '订单不存在或不属于当前买家' });
    }

    const order = orders[0];

    // 检查订单状态是否允许取消
    if (![0, 1, 2, 3].includes(order.status)) {
      return res.status(400).json({ success: false, error: '当前订单状态不允许取消' });
    }

    // 更新订单状态为已取消
    await db.execute(
      'UPDATE orders SET status = 5, updated_at = ? WHERE order_id = ?',
      [moment().format('YYYY-MM-DD HH:mm:ss'), order_id]
    );

    // 同步更新交易记录状态为失败
    await db.execute(
      'UPDATE transactions SET status = 2 WHERE order_id = ?',
      [order_id]
    );
    
    // 获取订单对应的商品ID
    const [orderDetails] = await db.execute(
      'SELECT product_id FROM orders WHERE order_id = ?',
      [order_id]
    );
    
    if (orderDetails.length > 0) {
      const productId = orderDetails[0].product_id;
      // 更新商品状态为在售
      await db.execute(
        'UPDATE products SET status = 1 WHERE product_id = ?',
        [productId]
      );
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家取消订单] 更新商品状态为在售，商品ID: ${productId}`);
    }

    // 记录取消日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [买家取消订单] 订单ID: ${order_id}, 买家ID: ${buyerId}, 原状态: ${order.status}`);

    res.json({ success: true, message: '订单已成功取消' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [买家取消订单失败] ${error.message}`);
    res.status(500).json({ success: false, error: '取消订单失败' });
  }
};